﻿using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Baidu.Aip.Speech;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace STT_Test_Plus.ViewModels;

public partial class BaiduDemoViewModel:ObservableObject
{
    const string APP_ID = "115807845";
    const string API_KEY = "fOZMajw1T8PJC5my2rFyxl8u";
    const string SECRET_KEY = "aIpPOZlZcgBWhJpQaKZLwwQR4HucyL1a";

    [ObservableProperty] private bool _isRecording;

    [ObservableProperty] private bool _isBusing;
    
    [ObservableProperty] private string _result;

    private CancellationTokenSource? _tokenSource=null;

    public RelayCommand RecordCmd { get; }

    private Asr client;
    public BaiduDemoViewModel()
    {
        RecordCmd = new RelayCommand(RecordOrStopRecord);
        client=new Asr(APP_ID,API_KEY,SECRET_KEY);
        client.Timeout = 60000;
    }

    private async void RecordOrStopRecord()
    {
        if (IsRecording)
        {
            _tokenSource?.Cancel();
        }
        else
        {
            //开始录制
            Result = "";
            _tokenSource = new CancellationTokenSource();
            IsRecording = true;
            string fileName=await MainWindowViewModel.Record(_tokenSource.Token);
            IsRecording = false;

            IsBusing = true;
            var obj= client.Recognize(File.ReadAllBytes(fileName), "wav", 16000);
            this.Result=obj.ToString();
            IsBusing = false;
        }
    }
}